package com.ist.dao;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

import com.ist.data.Data;
import com.ist.data.Vehicle;
import com.ist.smartmonitor.server.UpdateObserver;
import com.ist.smartmonitor.server.notify.AbstractDataEvent;
import com.ist.smartmonitor.server.notify.VehicleUpdateEvent;


public class VehicleDao {

	private static VehicleDao instance = null;
	
	private Data data = null;
	
	public VehicleDao() {
		JAXBContext context;
		try {
			context = JAXBContext.newInstance(Data.class);
			Unmarshaller unmarshaller = context.createUnmarshaller();
			unmarshaller.setSchema(null);
			this.data = (Data) unmarshaller.unmarshal(new File("data.xml"));
		} catch (JAXBException e) {
			e.printStackTrace();
		}

	}
	
	public static VehicleDao getInstance() {
		if(instance == null)
			instance = new VehicleDao();
		return instance;
	}
	
	protected void saveData() {
		JAXBContext context;
		try {
			context = JAXBContext.newInstance(Data.class);
			Marshaller marshaller = context.createMarshaller();
			marshaller.marshal(data, new FileWriter("data.xml"));
		} catch (JAXBException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public Integer saveOrUpdateVehicle(Vehicle vehicle) {
		int id = data.getVehicles().size();
		vehicle.setId(id);
		if(!data.getVehicles().contains(vehicle)) {
			data.getVehicles().add(vehicle);
		} else {
			data.getVehicles().remove(vehicle);
			data.getVehicles().add(vehicle);
		}
		saveData();
		UpdateObserver.getInstance().onVehicleEvent(new VehicleUpdateEvent(vehicle, 0));
		return vehicle.getId();
	}

	public void deleteVehicle(Vehicle vehicle) {
		data.getVehicles().remove(vehicle);
	}

	public List<Vehicle> findAllVehicles() {
		return data.getVehicles();
	}

	public Vehicle findVehicle(int vehicleId) {
		return data.getVehicles().get(vehicleId);
	}
}
